$(function () {
    $("#jqGrid").jqGrid({
        url: '/tts/sys/role/list',
        datatype: "json",
        colModel: [
            { label: '角色ID', name: 'id', width: 10, key: true },
            { label: '角色名称', name: 'name', width: 10 },
            { label: '状态', name: 'status', width: 10,formatter:function(value,options,row){
                if(value==="VALID"){
                    return '<span class="label label-primary">启用状态</span>';
                }
                if(value==="INVALID"){
                    return '<span class="label label-success">禁用状态</span>';
                }
            }},
            { label: '角色资源', name: 'menus', width: 30, formatter: function(value, options, row){
                var str = [];
                value.forEach(function(item,index,array){
                    str.push("<span class='label label-default' style='display: inline-block;font-size:12px'>"+item.name+"</span>")
                    if((index+1)%5==0)
                        str.push("<br>")
                });
                return str.join(" ");
            }}
        ],
        viewrecords: true,
        // height: 500,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});

// Ztree Settings
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "menuId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    },
    check: {
        enable: true
    }
};
var ztree;

var vm = new Vue({
    el:'#rrapp',
    mixins: [mixin],
    data:{
        showList: true,
        title: null,
        errorMsg:'',
        menuNames:"",
        role:{
            name:null,
            remark:"",
            status:"VALID",
            menus:[]
        },
        q:{
            name:null,
            status:'VALID'
        }
    },
    computed:{
        errorShow :function () {
            return this.errorMsg!='';
        }
    },
    methods: {
        search :function(){
            var json = getJSONObjectFromObject(vm.q);
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:json,
                page:page
            }).trigger("reloadGrid");
        },
        getMenu: function(menuId){
            //加载菜单树
            $.get("/tts/sys/menu/select", function(r){
                ztree = $.fn.zTree.init($("#menuTree"), setting, r.menuList);
                var menus = vm.role.menus
                var selectedNames = []
                menus.forEach(function(item,index){
                    var node = ztree.getNodeByParam("id",item.id)
                    ztree.checkNode(node,true,false)
                    selectedNames.push(item.name)
                })
                vm.menuNames = selectedNames.join()

            })
        },
        add: function(){
            vm.errorMsg=""
            vm.showList = false;
            vm.title = "新增";
            vm.role = {name:null,remark:null,menuNames:null,menus:[]};
            vm.getMenu();
        },
        update: function (event) {
            var menuId = getSelectedRow();
            if(menuId == null){
                return ;
            }

            $.get("/tts/sys/role/info/"+menuId, function(r){
                vm.showList = false;
                vm.title = "修改";
                vm.role = r.role
            });

            vm.getMenu();
        },
        valid:function(event){
            var menuIds = getSelectedRows();
            if(menuIds == null){
                return ;
            }
            var ids = [];
            menuIds.forEach(function(e){
                ids.push({name:"id",value:e})
            })
            confirm('确定要启用选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: "/tts/sys/role/valid",
                    data: ids,
                    contentType:'application/x-www-form-urlencoded; charset=UTF-8',
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        invalid: function (event) {
            var menuIds = getSelectedRows();
            if(menuIds == null){
                return ;
            }
            var ids = [];
            menuIds.forEach(function(e){
                ids.push({name:"id",value:e})
            })
            confirm('确定要禁用选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: "/tts/sys/role/invalid",
                    data: ids,
                    contentType:'application/x-www-form-urlencoded; charset=UTF-8',
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function (event) {
            var url =  "/tts/sys/role/save"
            var json = getJSONArrayFromObject(vm.role);
            $.ajax({
                type: "POST",
                url: url,
                contentType:'application/x-www-form-urlencoded; charset=UTF-8',
                data: json,
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        menuTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择菜单",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#menuLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getCheckedNodes();
                    //选择上级菜单
                    var selectedIds = []
                    var selectedNames = []
                    node.forEach(function(item){
                        selectedIds.push(item.id)
                        selectedNames.push(item.name)
                    })
                    vm.menuNames = selectedNames.join()
                    vm.role.menus = selectedIds
                    layer.close(index);
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page
            }).trigger("reloadGrid");
        }
    }
});